package com.blb.gateway_service.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 进行登录验证的过滤器
 */
@Component
public class UserLoginFilter extends ZuulFilter {

    /**
     * 返回过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        //前置过滤器
        return "pre";
    }

    /**
     * 过滤器顺序，越小越靠前
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行过滤，true和false用于指定run方法是否执行
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 核心过滤逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获得请求中的token参数
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        System.out.println("通过过滤:" + token);
        if(token == null){
            //返回状态码401，代表没有权限
            currentContext.setResponseStatusCode(401);
            //不响应请求
            currentContext.setSendZuulResponse(false);
        }
        return null;
    }
}
